/**
 * 获取各种AccessToken
 */
const {appID,appsecret} = require('./config');
const https = require('https');
//https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
function getAccessToken(){
    return new Promise((resolve,reject)=>{
        // https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
        https.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appID}&secret=${appsecret}`,res=>{
            let data = '';    
            res.on('data',chunk=>data += chunk);
            res.on('end',()=>{
                data = JSON.parse(data);
                data.expires_in = Date.now() + (res.expires_in - 300) * 1000;
                /*
                {
                    "access_token": "57_5ShnxIHlf0ZZ9c1GVe5_Ky5PXN8uRMADWghHJnzysRSn-b1DX95NtIFgCiSVJMQiyasA13uuuBOpt20I3tudJLs9MEWy0aqkYFvbKYTIi8b9XdCKE03e_z2g_kHdLkRr3PnSR1PrvRwT0uw1WWAaAEACCG",
                    "expires_in": 7200
                }
                */
                resolve(data.access_token);
            });
            res.on('error',err=>reject(err));
        })
    })
}

//通过code获取access_token
//https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
function getOauthAccessToken(CODE){
    return new Promise((resolve,reject)=>{
        https.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appID}&secret=${appsecret}&code=${CODE}&grant_type=authorization_code`,res=>{
            let data = "";
            res.on('data',chunk=>data += chunk);
            res.on('end',()=>{
                data = JSON.parse(data);
                resolve(data);
            });
            res.on('error',err=>reject(err));
        })
    })
}

module.exports = {
    getAccessToken,getOauthAccessToken
}